##########################################################################################################################
package WiganRL;
##### a mod_perl handler for Wigan-Warriors.com
##########################################################################################################################

##########################################################################################################################
######  TODO list  ######################################################################
##########################################################################################################################
#  
#
##########################################################################################################################

##########################################################################################################################
###### Bug list
##########################################################################################################################
##########################################################################################################################
#  Clicking on Login after Personal->My Details gives server error after apparently trying to add a new user
##########################################################################################################################

##########################################################################################################################
# Includes
##########################################################################################################################

use diagnostics;

use Apache2::Const qw(:common);
use Time::Local qw(timelocal);

use WiganRL::DataObject::User qw(:permissions);
use WiganRL::DataObject qw(:constants);
use WiganRL::DataObject::View;
use WiganRL::DataObject::Viewforum;
use WiganRL::DataObject::Viewwatch;
use WiganRL::DataObject::News;
use WiganRL::DataObject::Newssource;
use WiganRL::Thread;
use WiganRL::DataObject::Image;
use WiganRL::DataObject::UserContent;
use WiganRL::DataObject::Season;
use WiganRL::DataObject::Competition;
use WiganRL::DataObject::Matchstats;
use WiganRL::DataObject::Club;
use WiganRL::DataObject::Clubname;
use WiganRL::DataObject::Player;
use WiganRL::DataObject::Playersigning;
use WiganRL::DataObject::Playerposition;
use WiganRL::DataObject::Position;
use WiganRL::DataObject::Squad;
use WiganRL::DataObject::Score;
use WiganRL::DataObject::Stadium;
use WiganRL::DataObject::Ltable;
use WiganRL::DataObject::Dltable;
use WiganRL::DataObject::Ltablerow;
use WiganRL::DataObject::Injury;
use WiganRL::DataObject::Venue;
use WiganRL::DataObject::Referee;
use WiganRL::DataObject::Stafftype;
use WiganRL::DataObject::Squadstaff;
use WiganRL::DataObject::Statsgroup;
use WiganRL::DataObject::Vote;
use WiganRL::DataObject::Voteoption;
use WiganRL::DataObject::Usercolumn;
use WiganRL::DataObject::Page;
use WiganRL::DataObject::PageMargin;
use WiganRL::DataObject::Emoticon;
use WiganRL::DataObject::Userfavteam;
use WiganRL::DataObject::Userfavteamplayer;
use WiganRL::DataObject::Userteam;
use WiganRL::DataObject::Userteamplayer;
use WiganRL::DataObject::Teamplayerrating;
use WiganRL::DataObject::Admissionprice;
use WiganRL::DataObject::AVItem;
use WiganRL::DataObject::Playerfixedstats;
use WiganRL::DataObject::Playerfixedstatsscore;
use WiganRL::DataObject::Userip;
use WiganRL::DataObject::Tvchannel;
use WiganRL::Search;

use Diva::DB;
use Diva::Session;
use Diva::DataObject;

use CGI;
use CGI::Util qw(escape unescape);
use Crypt::CBC;
use Crypt::Blowfish;

use Carp;

use File::Basename;
use File::Spec;

#use strict;
#use warnings;
no warnings 'uninitialized';

local $SIG{__WARN__} = \&Carp::cluck;  #full call back trace

#print "Content-type: text/html\n\n";

##########################################################################################################################
# site setup and location variable declarations
##########################################################################################################################

my ($SITE_BASE_URL,$SITE_BASE_DIR,$CGI_BASE_URL,$CGI_BASE_DIR,$EMAIL_BASE_DIR,$MAIL_SMTP_SERVER);
my ($SEND_EMAILS,$ADMIN_NAME,$ADMIN_EMAIL,$MAIL_SCRIPT,$SITE_DATA_DIR);
my ($DATABASE_NAME,$DATABASE_SERVER,$DATABASE_USERNAME,$DATABASE_PASSWORD,$DATABASE_TYPE);

load_config('wiganrl.ini');

my $USER_UPLOADDIR= "$SITE_DATA_DIR/users";
my $USER_UPLOADURL= "data/users";
my $SEARCH_DATE_DAYS= 3;

#control main club of site with variable;
my $CLUB_ID= 10043;

##########################################################################################################################
# mod_perl handler function starts here
##########################################################################################################################

$|++;  #unbuffered

sub handler { 
	print "Content-type: text/html\n\n<h1>Got here</h1>";
}

sub handler2 {

my $r = shift;  #request object
	
##########################################################################################################################
# class and database setup
##########################################################################################################################

my $cgi= CGI->new($r);
$cgi->param('CGI_BASE_URL',$CGI_BASE_URL);
#print "Content-Type: text/html\n\n";
#print "Status: ".$cgi->param('status');

my $dbh= Diva::DB->new();
$dbh->set( {
	DATABASE_NAME       => $DATABASE_NAME,
	DATABASE_SERVER     => $DATABASE_SERVER,
	DATABASE_USERNAME   => $DATABASE_USERNAME,
	DATABASE_PASSWORD   => $DATABASE_PASSWORD,
	DATABASE_TYPE       => $DATABASE_TYPE,
	} );
$dbh->connect();
$dbh->debug(0);

#use Devel::Profile;
#use DBIx::Profile;
#$dbh->handle->setLogFile('c:/wwcom/v2.0/cgi-bin/db.log');

#ordering of these lines is important!
WiganRL::DataObject->dbh($dbh);
WiganRL::DataObject->cgi($cgi);

Diva::DataObject->init_contenttypes('WWCOM');  #loads contenttypes

WiganRL::DataObject->init_class();
WiganRL::Search->init_class();

WiganRL::DataObject->session(undef); #reset session - is this neccessary?
WiganRL::Search->dbh($dbh);
#WiganRL::DataObject::User->dbh($dbh);
WiganRL::DataObject->cachedir("$SITE_BASE_DIR/cached");
WiganRL::DataObject->datadir($SITE_DATA_DIR);
WiganRL::DataObject->dataurl('data');
WiganRL::DataObject->site_clubid(10043);
Diva::DataObject->template_dir("$SITE_BASE_DIR/templates");

#print "Status: ".$cgi->param('status');


##########################################################################################################################
# setup session
##########################################################################################################################

my $session= Diva::Session->new;
#print "Content-type: text/html\n\n";
#$session->debug(1);
$session->dbh($dbh);
$session->cgi($cgi);
$session->fields(['UserID']);
$session->history_fields(['ObjectID','status','UserID','SessionID']);

#output %ENV
#map {carp "ENV: $_ = $ENV{$_}"} keys %ENV;

my $cookies= 0;
my $session_cookie= undef;

#get session id either from cookie or cgi or do cookies test
if ($cgi->cookie('WR_SESSION_ID') ne '') {
	#print "Cookie Session: ".$cgi->cookie('WR_SESSION_ID');
	$session->load($cgi->cookie('WR_SESSION_ID'));
	#print "Decoded: ".$session->decoded_id;
	$cookies= 1;
} elsif ($cgi->param('SessionID') ne '') {
	#print "Session ID: ".$cgi->param('SessionID');
	$session->load($cgi->param('SessionID'));
	$cookies= 0;
} elsif ($cgi->param('CookieTest') ne '') {  #cookie test result
	if ($cgi->cookie('WR_CT') ne '') {
		$cookies= 1;
	}
} else {  #do cookie test
	my $cookie= $cgi->cookie(
		-name=>'WR_CT',
		-value=> 1,
		-expires=> "+1m");  #expires in one minute
	print "Content-type: text/html\n\n";
	print $cgi->redirect(
		 -uri=>"$CGI_BASE_URL/wiganrl?".$cgi->query_string."&CookieTest=True",
		 -nph=>0,
		 -cookie=>$cookie);   #non-parsed header
#	return OK;
      return 1;
	  #exit(0);
}

$cgi->delete('SessionLink');
$cgi->delete('SessionID');

if ($session->loaded && $session->active) {
	$session->to_cgi;
} elsif ($session->loaded) {  #inactive session that has been loaded
	$session->activate;
} else {    #no session loaded
	$session->from_cgi;
}
$session->update;
$session_cookie= $cgi->cookie(
	-name=>'WR_SESSION_ID',
	-value=> $session->id);  #expires when user closes browser
$cgi->param('CGI_HEADER',"Set-Cookie: ".$session_cookie->as_string);
$session->cookies($cookies);  #remember if this is a cookie controlled session
	
#carp "CGI_HEADER: ".$cgi->param('CGI_HEADER');
if (!$cookies) {
	$cgi->param('SessionID',$session->id);    
	$cgi->param('SessionLink',"&SessionID=".$session->id);
}

#tell dataobjects about session
WiganRL::DataObject->session($session);
#update what we are looking at now.
$session->add_history;

##########################################################################################################################
# setup status from cookie data
##########################################################################################################################
my $st= $cgi->cookie('WR_FORWARD_STATUS');
if (defined $st && $st ne '') {
	# format of FORWARD_STATUS:
	#   ?<&name=val&name=val ...>
	$st=~ s/^\?//;
	my @pairs= split(/\&/,$st);  #first is just status
	#$cgi->param('status',$pairs[0]);
	for (@pairs) {  #then name/value cgi-pairs
		my ($name,$value)= split(/\=/,$_);
		$cgi->param($name,$value);
	}
}

##########################################################################################################################
# setup page object 
##########################################################################################################################
my $page= WiganRL::DataObject::Page->new();
$page->template("Page.Normal.html");
$page->data('SITE_BASE_URL',$SITE_BASE_URL);
$page->data('CGI_BASE_URL',$CGI_BASE_URL);
#set page style
$cgi->cookie('WR_STYLE') ne '' ? 
	$page->data('STYLE',$cgi->cookie('WR_STYLE')) :
	$page->data('STYLE','2007home');


##########################################################################################################################
# load user from session by id / login from cookie info
##########################################################################################################################
my $user= WiganRL::DataObject::User->new;
my $uid= $session->data('UserID');
if ($cgi->param('status')!~ /^Site\.Login/ && $cgi->param('status')!~ /^Site\.Register/
	and $cgi->param('status')!~ /^Site\.Logoff/) {  #don't load user if doing a login, logoff or registration status
	if (defined($uid) && $uid ne '') {  #if logged in load from id
		$user= $user->load($uid);
		WiganRL::DataObject->user($user);
#	} elsif ($cgi->cookie('WR_USER_LOGIN')=~ /true/i &&
#		$cgi->cookie('WR_USER_NAME') ne '' && $cgi->cookie('WR_USER_PASSWORD') ne '') {  #if asking to login a user from cookie data
	} elsif (defined ($cgi->cookie('WR_USER_LOGIN')) and $cgi->cookie('WR_USER_LOGIN') ne  '') {  #if asking to login a user from cookie data
		my @cdata= split(',',$session->decrypt($cgi->cookie('WR_USER_LOGIN')));
		$cgi->param('USER_NAME',$session->decrypt($cdata[0])); 
		$cgi->param('USER_PASSWORD',$session->decrypt($cdata[1]));
		$cgi->param('next_status',$cgi->param('status'));
		$cgi->param('status','Site.Login.Login');
	}
}

if ($user->loaded) {
	my $newcontent= '';
	my $history= $session->history->{'ObjectID'};
	unshift @$history,$cgi->param('ObjectID');
	if ($user->new_content('NEWS',$history)) {
	   $newcontent.= ', ' if ($newcontent ne '');
	   $newcontent.= qq~<A href="$CGI_BASE_URL?status=News~.$cgi->param('SessionLink').qq~"><b>News</b></a>~;
	}
	if (my $id= $user->new_content('VIEW',$history) && $cgi->param('status') !~ /ALLREADALLFORUMS/) {
	   $newcontent.= ', ' if ($newcontent ne '');
	   $newcontent.= qq~<A href="$CGI_BASE_URL?status=Views.Forums~.$cgi->param('SessionLink').qq~"><b>Messages</b></a>~;
#		if ($user->data('USER_VIEW_SINGLEFORUM') eq 'True') {
#		   $newcontent.= qq~<A href="$CGI_BASE_URL?status=Views.Forums~.$cgi->param('SessionLink').qq~"><b>Messages</b></a>~;
#		} else {  #link to appropriate forum
#		   my $lp= WiganRL::DataObject::View->new($id);
#		   $newcontent.= qq~<A href="$CGI_BASE_URL?status=Object.VIEWFORUM\&ObjectID=~.$lp->viewforum->id.$cgi->param('SessionLink').qq~"><b>Messages</b></a>~;
#		}
	}
	$newcontent= qq~<span class="usermenu">Unread Content: $newcontent</span>~ if ($newcontent ne '');
	$user->data('NEW_CONTENT',$newcontent);    
	#carp "New Content: ".$user->data('NEW_CONTENT');
	$user->uploaddir($USER_UPLOADDIR);
	$user->uploadurl($USER_UPLOADURL);
}

#add admin actions
if ($user->loaded) {
  #  my $o= WiganRL::DataObject->new();
	$user->template("User.Menus.html");
	$user->parent($page);
	#$o->search_objects(1);  # allow recursion to parent
	
	#check administrator privs
	my $mask= 1;
	#print "Content-type: text/html\n\n";
   # for (@types) {
		
		#print "<pre>$_: ".$user->permission($_,$USERPERM_SUPERADMIN)."</pre>";
   #     $mask= $mask && $user->permission($_,$USERPERM_SUPERADMIN);
   # }
	#if ($mask) {
	#    my $o2= WiganRL::DataObject->new();
	#    $o2->template("Admin.Menu.html");
	#    $o->data('ADMIN_MENU',$o2->output);
	#}
	$page->data("USER_MENUS",$user->output);
}

##########################################################################################################################
# default status if still empty
##########################################################################################################################

if ($cgi->param('status') eq '') {
	$cgi->param('status','Home');
}

#add menus
my $o= WiganRL::DataObject->new();
$o->template("Site.Menu.html");
$page->data("SITE_MENU",$o->output);

#add heading
$o= WiganRL::DataObject->new();
$o->template("Site.Title.html");
$page->data("SITE_TITLE",$o->output);

#add copyright
$o= WiganRL::DataObject->new();
$o->template("Site.Copyright.html");
$page->data("SITE_COPYRIGHT",$o->output);


#allow fields from children to be searched
#$page->search_objects(1);


##########################################################################################################################
# Check Admin access only if user loaded 
##########################################################################################################################

if ($cgi->param('status')=~ /^Admin/ && !$user->loaded) {      #no user but trying to use admin pages
	$cgi->param('status','Site.Login');
}

#add user login box
my $status= $cgi->param('status') ? ($cgi->param('status')) : '';
if (!$user->loaded && $status!~ /^(Site\.Login)|(Site\.Register)/) {
	$o= WiganRL::DataObject->new();
	$o->template("User.Login.Snip.html");
	$page->data("USER_LOGIN",$o->output);
}

#now add user content at top
my $uc= WiganRL::DataObject::UserContent->new($cgi->param('status'));
$uc->admin_edit_output(1);
$page->add_object($uc,"UserContent.Header.html");


##########################################################################################################################
# now switch on status
##########################################################################################################################

##########################################################################################################################
##########################################################################################################################
# Site statuses 
##########################################################################################################################

##########################################################################################################################
# Home page
##########################################################################################################################
if ($cgi->param('status')=~ /^Home/) {      #Home Page    
		WiganRL::DataObject::Matchstats->objects_template('WiganRL::DataObject::News',"News.Related.html");
		WiganRL::DataObject::Matchstats->related_template('WiganRL::DataObject::View',"View.Related.html");
		
##########################################################################################################################
# Latest News list
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^News(?:\.([^\.]*))?(?:\.(.*))?$/) {    #Latest News page
	my $type= $1;
	my $id= $2;
	$type= undef if ($type eq '');
	
	my $search= WiganRL::Search->new;   
	my $typestr= $type; 
	$typestr= 'News' if (!defined $type);
	if ($typestr!~ /s$/) {
		$typestr= $typestr.'s';
	}
	
	my $startdate;
	if (defined $id && $id != 0) {
		$search->clear; $search->table('NEWS');
		$search->where("PK_OBJECT_ID = $id");
		$startdate= $search->search->[0]->data('OBJECT_DATE');
	}
	
	my $list= WiganRL::DataObject->new;
	$search->clear; $search->table('NEWS');
	my $where= '';
	$where.= "OBJECT_DATE<='$startdate'" if (defined $startdate);
	$where.= ' and ' if ($where && defined $type);
	$where.= "NEWS_TYPE = '$type'" if (defined $type);
	$search->orderby('OBJECT_DATE desc');
	$search->where($where);
	my $latest= $search->search(15);
	foreach (@$latest) {
		if ($_->data('NEWS_OFFSITE') eq 'True') {
			$list->add_object($_,"News.Offsite.Snip.html");
		} else {
			$list->add_object($_,"News.Snip.html");
		}
	}
	$list->data('ADMIN_LINK_NEWS',WiganRL::DataObject::News->new()->get_field('ADMIN_LINK_NEWS'));    
	$list->data('TYPE',$type);
	$list->data('TYPESTR',$typestr);
	#last story
	$list->data('OLD_ID',$latest->[$#$latest]->id);    
	#start of previous page    
	$search->clear; $search->table('NEWS');
	$where= '';
	$where.= "OBJECT_DATE>'$startdate'" if (defined $startdate);
	$where.= ' and ' if ($where && defined $type);
	$where.= "NEWS_TYPE = '$type'" if (defined $type);
	$search->where($where);
	$search->orderby('OBJECT_DATE');
	$latest= $search->search(14);
	$list->data('NEW_ID',$latest->[$#$latest]->id) 
		if ($#$latest >= 0);
	$page->add_object($list,"News.List.html");    
	$page->add_object(WiganRL::DataObject->new,"Search.News.html");
	

##########################################################################################################################
# News source list
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Newssources/) {
	my $search= WiganRL::Search->new('NEWSSOURCE');   
	
	my $list= WiganRL::DataObject->new;
	my $latest= $search->latest(5);
	foreach (@$latest) {
		$list->add_object($_,"Newssource.Snip.html");
	}
	$list->data('ADMIN_LINK_NEWSSOURCE',WiganRL::DataObject::Newssource->new()->get_field('ADMIN_LINK_NEWSSOURCE'));
	$page->add_object($list,"Newssource.List.html");

##########################################################################################################################
# Squads/Injuries/Reports/Fixtures from squad
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^(Squads|Injuries|Reports|Fixtures)(\.([\d]+))?/) { 
	my $type= $1;
	my $sid= $3;  #squad

	#wide page
	$page->template('Page.Wide.html');

	my $squad= getSquad($sid);
	if ($type eq 'Squads') {
		$page->template("Page.Normal.html");
		$squad->objects_template('WiganRL::DataObject::Squadplayer',"$SITE_BASE_DIR/templates/Player.Snip.html");
		$squad->objects_template('WiganRL::DataObject::Squadstaff',"$SITE_BASE_DIR/templates/Squadstaff.Snip.html");
		$squad->add_object(WiganRL::DataObject->new,"Search.Player.html");
		my $cv= $squad->cacheVar('SQUAD_SQUADPLAYERS');  #TODO: clearing cached vars when appropriate
		if ($cv ne '') {
			$squad->data('SQUAD_SQUADPLAYERS',$cv);
		}
		$page->add_object($squad,"Squad.html");
	} elsif ($type eq 'Injuries') {
		$squad->objects_template('WiganRL::DataObject::Squadplayer',"$SITE_BASE_DIR/templates/Player.Injury.Snip.html");
		WiganRL::DataObject::Player->objects_template('WiganRL::DataObject::Injury',"$SITE_BASE_DIR/templates/Injury.Snip.html");
		$page->add_object($squad,"Squad.Injuries.html");
	} elsif ($type eq 'Reports') {
		$squad->objects_template('WiganRL::DataObject::Matchstats',"$SITE_BASE_DIR/templates/Matchstats.Snip.html");
		WiganRL::DataObject::Matchstats->related_template('WiganRL::DataObject::News',"News.Related.html");
		WiganRL::DataObject::Matchstats->objects_template('WiganRL::DataObject::News',"News.Related.html");
		$page->add_object($squad,"Squad.Reports.html");
	} else {
		$squad->objects_template('WiganRL::DataObject::Matchstats',"$SITE_BASE_DIR/templates/Matchstats.Fixtures.Row.html");
		$page->add_object($squad,"Squad.Fixtures.html");
	}


##########################################################################################################################
# Tables from a season
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Tables(\.([\d]+))?/) {
	my $sid= $2;  #season
	my $season= getSeason($sid);
		
	my $s= WiganRL::DataObject->search;
	$s->clear; $s->table('COMPETITION');
	$s->where("FK_PARENT_ID=".$season->id);
	for (@{$s->search}) {
		my $s= WiganRL::Search->new;
		$s->clear; $s->table('LTABLE');
		$s->where("FK_COMPETITION_ID='".$_->id."'");
		for (@{$s->search}) {
			my $lt= $_;
			my $s= WiganRL::Search->new;
			$s->clear; $s->table('DLTABLE'); $s->where('FK_LTABLE_ID='.$lt->id); $s->orderby('DLTABLE_DATE desc');
			my $res= $s->search;
			if ($#$res >= 0) {
				my $o= $$res[0];
				$o->objects_template('WiganRL::DataObject::Ltablerow',"$SITE_BASE_DIR/templates/Ltablerow.Margin.html");
				$page->add_object($o,"Dltable.Snip.html");
			}
		}
	}
	$page->objects_template('WiganRL::DataObject::Ltable',"$SITE_BASE_DIR/templates/Ltable.Snip.html");


##########################################################################################################################
# Images 
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Images/) {    #Latest Images
	my $list= WiganRL::DataObject->new;
	my $s= WiganRL::DataObject->search;
	$s->clear; $s->table('IMAGE'); 
	$s->orderby('IMAGE_DATE desc');
	for (@{$s->search(15)}) {
		$list->add_object($_,"Image.Snip.html");
	}
	$list->data('ADMIN_LINK_IMAGE',WiganRL::DataObject::Image->new->get_field('ADMIN_LINK_IMAGE'));    
	$page->add_object($list,"Image.List.html");
	$page->add_object(WiganRL::DataObject->new,"Search.Image.html");

##########################################################################################################################
# AVItems
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^AVItems/) {    #Latest AVItems
	my $list= WiganRL::DataObject->new;
	my $s= WiganRL::DataObject->search;
	$s->clear; $s->table('AVITEM'); 
	$s->orderby('AVITEM_DATE desc');
	for (@{$s->search(15)}) {
		$list->add_object($_,"AVItem.Snip.html");
	}
	$list->data('ADMIN_LINK_AVITEM',WiganRL::DataObject::AVItem->new->get_field('ADMIN_LINK_AVITEM'));    
	$page->add_object($list,"AVItem.List.html");
	$page->add_object(WiganRL::DataObject->new,"Search.AVItem.html");

##########################################################################################################################
# Message Board
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Views\.Forums/) {    #Views forums page
	if ($user->data('USER_VIEW_SINGLEFORUM') eq 'True') {
		my $s= WiganRL::DataObject->search;   
		$s->clear; $s->table('VIEWFORUM');
		$s->where('VIEWFORUM_ORDER=2');
		my $res= $s->search;
		print $cgi->redirect(
			-uri=>"$CGI_BASE_URL?status=Object.VIEWFORUM\&ObjectID=".
				$res->[0]->id.$cgi->param('SessionLink'),
			-nph=>0,
			-cookie=>$session_cookie);   #non-parsed header
		return;		
	}

	my $list= WiganRL::DataObject->new;
	my $s= WiganRL::DataObject->search;   
	$s->clear; $s->table('VIEWFORUM');
	$s->orderby('VIEWFORUM_ORDER');
	my $history= $session->history->{'ObjectID'};
	for (@{$s->search}) {
        my ($sth,$rv)= $dbh->get(['VIEW_THREAD','VIEW'],['*'],'',
			"VIEW_THREAD.FK_HEAD_ID=VIEW.FK_OBJECT_ID and ".
			"FK_VIEWFORUM_ID=".$_->id,'',"VT_LASTPOST_DATE desc",'',1);
		if ($rv>0) {
			my $res= $sth->fetchrow_hashref;
			my $lp= WiganRL::DataObject::View->new($res->{'VT_LASTPOST_ID'});
			$_->data('LAST_POST_ID',$res->{'VT_LASTPOST_ID'});
		    $_->data('LAST_POST_DATE',$lp->get_field('OBJECT_F_DATE_SHORT').
				' at '.$lp->get_field('OBJECT_F_TIME'));
		    $_->data('LAST_POST_AUTHOR_ID',$lp->get_field('FK_USER_ID'));
		    $_->data('LAST_POST_AUTHOR',$lp->get_field('VIEW_AUTHOR'));
			if ($_->unread_content($history)) {
	            $_->data('VIEWFORUM_HIGHLIGHT','highlightb');
                $_->data('LAST_POST_OBJECT_NEW_IMAGE', 
					qq~<img src="images/view_new.gif" alt="Unread Threads">~);
			} else {
                $_->data('LAST_POST_OBJECT_NEW_IMAGE',
					qq~<img src="images/view.gif" alt="No Unread Threads">~);
			}
		}
		$list->add_object($_,"Viewforum.Link.html");
		$sth->finish;
	}
	#TODO: add motm votes to this list
	$page->add_object($list,"Viewforums.List.html");


} elsif ($cgi->param('status')=~ /^Views\.List(\.(\w+))?/) {    #Views page

	print $cgi->redirect(
		-uri=>"$CGI_BASE_URL?status=Views.Forums".
			$cgi->param('SessionLink'),
		-nph=>0,
		-cookie=>$session_cookie);   #non-parsed header
	return;

	
	my $sno= $2;
	$page->template("Page.Wide.html");
	my $list= WiganRL::DataObject->new;
	
	#get cached field from object
	my $o= WiganRL::DataObject::View->new;
	my $objects= undef;
	if ($sno eq 'ALLREAD') {
		my @now= localtime;
		my $now= sprintf("%04d%02d%02d%02d%02d%02d",$now[5]+1900,$now[4]+1,$now[3],$now[2],$now[1],$now[0]);
		$user->set_lastvisit($now);
		$sno= 0;
	}
	if ($sno) {
		$objects= $o->cacheVar("Views.List.OBJECTS.$sno");
	} else {
		$objects= $o->cacheVar('Views.List.OBJECTS');
	}
	$list->data('ADMIN_LINK_NEWTOPIC',$o->get_field('ADMIN_LINK_NEWTOPIC'));
	$list->data('OBJECTS',$objects);
	my $oarr= $o->objects;
	#last thread
	$list->data('NEW_THREAD_ID',$oarr->[0]->{Object}->id);
	$list->data('OLD_THREAD_ID',$oarr->[$#$oarr]->{Object}->id);    
	$page->add_object($list,"View.List.html");
	$page->add_object(WiganRL::DataObject->new,"Search.View.html");
	

##########################################################################################################################
# Votes
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Votes$/) {    
	my $list= WiganRL::DataObject->new;
	my $s= WiganRL::DataObject->search;   
	$s->clear; $s->table('VOTE');
#    $s->orderby('VOTE_EXPIRES desc');
	$s->orderby('OBJECT_MODIFIED_DATE desc');
	for (@{$s->search}) {
		$list->add_object($_,"Vote.Snip.html");
	}
	#TODO: add motm votes to this list
	$list->data('ADMIN_LINK_VOTE',WiganRL::DataObject::Vote->new()->get_field('ADMIN_LINK_VOTE'));    
	$page->add_object($list,"Vote.List.html");

##########################################################################################################################
# Opinions Columns
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Columns$/) {    #user columns list
	#find columnists
	my $list= WiganRL::DataObject->new;
	my $s= WiganRL::DataObject->search;
	$s->clear; $s->table('USER');
	for (@{$s->search}) {
		if ($_->userpermission('USERCOLUMN',undef,$USERPERM_CONTRIB)) {
			$_->objects_template("WiganRL::DataObject::Usercolumn","$SITE_BASE_DIR/templates/Usercolumn.Snip.User.html");
			$list->add_object($_,"User.Columnist.html");
		}
	}
	$list->data('ADMIN_LINK_USERCOLUMN',WiganRL::DataObject::Usercolumn->new()->get_field('ADMIN_LINK_USERCOLUMN'));    
	$page->add_object($list,"Usercolumn.List.html");
	$page->add_object(WiganRL::DataObject->new,"Search.Usercolumn.html");


##########################################################################################################################
# Pick Team
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Userteam$/) {    #user columns list
	#find columnists
	my ($sth,$rv)= $dbh->get(['SQUAD','OBJECT','SEASON'],['PK_OBJECT_ID'],"",
	   "SEASON_ACTIVE='True' and SEASON.FK_OBJECT_ID=FK_SEASON_ID and 
		SQUAD.FK_OBJECT_ID=PK_OBJECT_ID and SQUAD.FK_CLUB_ID=".WiganRL::DataObject->site_clubid,"","SQUAD_ORDER");
	my $reshash= $sth->fetchrow_hashref;
	my ($match);

	my ($next,$last)= (undef,undef);
	#get next match and previous match
	my $s= WiganRL::DataObject->search;
	$s->clear(); $s->table('MATCHSTATS');
	$s->where('MATCH_KOTIME > NOW() and
		(FK_HOMESQUAD_ID = '.$$reshash{PK_OBJECT_ID}.' or
		FK_AWAYSQUAD_ID = '.$$reshash{PK_OBJECT_ID}.')');
	$s->orderby('MATCH_KOTIME');  #next match
	$s->limit(1);
	my $res= $s->search;
	if ($#$res>=0) {
		$next= $res->[0];
	}    
	$sth->finish;
	if (defined $next) {
			print $cgi->redirect(
				-uri=>"$CGI_BASE_URL/wiganrl?status=Admin.Edit.Object.USERTEAM\&ParentID=".$next->id.
					$cgi->param('SessionLink'),
				-nph=>0,
				-cookie=>$session_cookie);   #non-parsed header
			return;
	} else {
		#TODO: catch error - no next match
		return;
		;
	}

##########################################################################################################################
# Man of the Match
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Manofthematch$/) {    #player ratings and motm votes
	my ($sth,$rv)= $dbh->get(['SQUAD','OBJECT','SEASON'],['PK_OBJECT_ID'],"",
	   "SEASON_ACTIVE='True' and SEASON.FK_OBJECT_ID=FK_SEASON_ID and 
		SQUAD.FK_OBJECT_ID=PK_OBJECT_ID and SQUAD.FK_CLUB_ID=".WiganRL::DataObject->site_clubid,"","SQUAD_ORDER");
	my $reshash= $sth->fetchrow_hashref;
	my ($match);

	my ($next,$last)= (undef,undef);
	#get next match and previous match
	my $s= WiganRL::DataObject->search;
	$s->clear(); $s->table('MATCHSTATS');
	$s->where('MATCH_KOTIME <= NOW() and
		(FK_HOMESQUAD_ID = '.$$reshash{PK_OBJECT_ID}.' or
		FK_AWAYSQUAD_ID = '.$$reshash{PK_OBJECT_ID}.')');
	$s->orderby('MATCH_KOTIME desc');  #last match
	$s->limit(1);
	my $res= $s->search;
	if ($#$res>=0) {
		$last= $res->[0];
	}    
	$sth->finish;
	if (defined $last) {
			print $cgi->redirect(
				-uri=>"$CGI_BASE_URL/wiganrl?&status=Object.MATCHSTATS.Manofthematch\&ObjectID=".$last->id.
					$cgi->param('SessionLink'),
				-nph=>0
				-cookie=>$session_cookie);   #non-parsed header
			exit(0);    
	} else {
		#TODO: catch error - no last match
		return;
	}

##########################################################################################################################
# Chat
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Chat$/) {
	$page->add_object(WiganRL::DataObject->new,"Chat.html");
	$page->template("Page.Wide.html");
} elsif ($cgi->param('status')=~ /^Chat.Popup/) {
	$page->add_object(WiganRL::DataObject->new,"Chat.Popup.html");
	$page->template("Page.Popup.html");

##########################################################################################################################
# Venues 
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Venues/) {
	my $list= WiganRL::DataObject->new;
	my $s= WiganRL::DataObject->search;   
	$s->clear; $s->table('VENUE');
	foreach (@{$s->search}) {
		$list->add_object($_,"Venue.Snip.html");
	}
	$list->data('ADMIN_LINK_VENUE',WiganRL::DataObject::Venue->new()->get_field('ADMIN_LINK_VENUE'));    
	$page->add_object($list,"Venue.List.html");
	$page->add_object(WiganRL::DataObject->new,"Search.Venue.html");

##########################################################################################################################
# Stadia 
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Stadia/) {
	my $list= WiganRL::DataObject->new;

	my $season= getSeason();
	
	#sites main club stadia first
	my $s= WiganRL::DataObject->search;   
	$s->clear; $s->table('SQUAD');
	$s->where("FK_SEASON_ID='".$season->id."' and FK_CLUB_ID='$CLUB_ID'");
	$s->orderby("SQUAD_ORDER");
	for (@{$s->search}) {
		if (defined ($_->stadium) && $_->stadium->loaded) {
			$list->add_object($_,"Squad.Stadium.Snip.html");
		}
	}
		#for each other club in order
	$s->clear; $s->table('CLUB');
	$s->where("FK_OBJECT_ID != '$CLUB_ID'");
	$s->orderby('CLUB_NAME');
	for (@{$s->search}) {
		my $s= WiganRL::Search->new;   
		$s->clear; $s->table('SQUAD');
		$s->where("FK_SEASON_ID='".$season->id."' and FK_CLUB_ID='".$_->id."'");
		$s->orderby("SQUAD_ORDER");                    
		foreach (@{$s->search}) {
			if (defined ($_->stadium) && $_->stadium->loaded) {
				$list->add_object($_,"Squad.Stadium.Snip.html");
			}
		}
	}
	$list->data('ADMIN_LINK_STADIUM',WiganRL::DataObject::Stadium->new()->get_field('ADMIN_LINK_STADIUM'));    
	$page->add_object($list,"Stadium.List.html");
	$page->add_object(WiganRL::DataObject->new,"Search.Stadium.html");
	
##########################################################################################################################
# Help
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Help./) {
	$page->add_object(WiganRL::DataObject->new,"Help.Popup.html");
	$page->template("Page.Popup.html");

##########################################################################################################################
# Archived seasons
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Seasons$/) {
	my $list= WiganRL::DataObject->new;
	my $s= WiganRL::DataObject->search;   
	$s->clear; $s->table('SEASON');
	$s->orderby('SEASON_STARTDATE');
	for (@{$s->search}) {
		$list->add_object($_,"Season.Snip.html");
	}
	$list->data('ADMIN_LINK_SEASON',WiganRL::DataObject::Season->new()->get_field('ADMIN_LINK_SEASON'));    
	$page->add_object($list,"Season.List.html");
		
##########################################################################################################################
# Coaches - TODO
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Coaches(\.([\d]+))?/) {  


##########################################################################################################################
# Message Board
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^View\.(\d+)\.Related\.([A-Z]+)/) {  
	$page->template('Page.Popup.html');
	#$page->add_object(WiganRL::DataObject::View->new($1);

} elsif ($cgi->param('status')=~ /^Emoticons.Popup/) {
	$page->add_object(WiganRL::DataObject::View->new,"Emoticons.Popup.html");    
	$page->template("Page.Popup.html");

##########################################################################################################################
# Search
##########################################################################################################################

} elsif ($cgi->param('status')=~ /^SearchPage/) {
	$page->add_object(WiganRL::DataObject->new,"Search.html");

} elsif ($cgi->param('status')=~ /^Search/) {
	my $list= WiganRL::DataObject->new;

	my $s= WiganRL::DataObject->search;
	my $nres= 0;
	for ($cgi->param('SEARCH_TABLE')) {
		$s->clear; $s->table($_);
		my $type= $_;
		$type=~ s/(\w+)/\u\L$1/g;  #title case
		my $class= 'WiganRL::DataObject::'.$type;

		my $obj= $class->new;
		my $where= '';
		if ($cgi->param('SEARCH_TEXT') ne '') {
			for my $field (@{$obj->search_fields}) {
				my $twhere= '';
				my $sstr= $cgi->param('SEARCH_TEXT');
				while ($sstr=~ /\"([^\"]+)\"/g) {
					$twhere.= ' and ' if ($twhere ne '');            
					$twhere.= "$field like ".WiganRL::DataObject->dbh->handle->quote("%$1%");
				}
				$sstr=~ s/\"[^\"]+\"//eg;
				for my $term (split(/\s+/,$sstr)) {
					$twhere.= ' and ' if ($twhere ne '');            
					$twhere.= "$field like ".WiganRL::DataObject->dbh->handle->quote("%$term%");
				}
				if ($twhere ne '') {
					$where.= ' or ' if ($where ne '');
					$where.= '(';
					$where.= $twhere.')';
				}
			}
			$where= "($where)" if ($where ne '');

		}
		if ($cgi->param('SEARCH_STARTDATE')) {
			$where.= ' and ' if ($where ne '');
			$where.= " OBJECT_DATE>='".$cgi->param('SEARCH_STARTDATE')."'";
		}
		if ($cgi->param('SEARCH_ENDDATE')) {
			$where.= ' and ' if ($where ne '');
			$where.= " OBJECT_DATE<='".$cgi->param('SEARCH_ENDDATE')."'";
		}
		carp $type;
		carp $cgi->param('SEARCH_NEWSTYPE');
		if ($type eq "NEWS" && $cgi->param('SEARCH_NEWSTYPE')) {
			$where.= ' and ' if ($where ne '');
			$where.= ' (';
			my @nts;
			for ($cgi->param('SEARCH_NEWSTYPE')) {
				$nts[$#nts+1]= " NEWS_TYPE='".$_."'";
			}
			$where.= join(@nts,' or ').') ';
		}
		carp $where;

		$s->where($where) if ($where ne '');
		$s->orderby($cgi->param('SEARCH_ORDERBY'));
		#$s->debug(1);
		my $res= $s->search;
		for (@$res) {
			if ($type eq 'NEWS' && $_->data('NEWS_OFFSITE') eq 'True') {
				$list->add_object($_,"News.Offsite.Snip.html");
			} else {
				$list->add_object($_,"$type.Snip.html");            
			}
			
		}
		$nres+= $#$res+1; 
		#$s->debug(0);
	}
	if ($nres<=0) {
		$list->add_object(WiganRL::DataObject->new,"Search.None.html");
	}
	$page->add_object($list,"Search.List.html");


##########################################################################################################################
# Player output pages
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Player\.(\w+)\.([\d]+)/) {
	my $type= $1;
	my $pid= $2;  #player
	my $o= WiganRL::DataObject::Player->new($pid);
	if ($type eq 'Profile') {
		$o->template("Player.html");
	} elsif ($type eq 'Injuries') {
		$o->template("Player.Injuries.html");
		$o->objects_template('WiganRL::DataObject::Injury',"$SITE_BASE_DIR/templates/Injury.Snip.html");
	} elsif ($type eq 'Signings') {
		$o->template("Player.Signings.html");
		$o->objects_template('WiganRL::DataObject::Playersigning',"$SITE_BASE_DIR/templates/Playersigning.Snip.html");
	} elsif ($type eq 'AllMatches') {
		$o->template("Player.AllMatches.html");
		WiganRL::DataObject::Teamplayerscore->template("Teamplayerscore.String.html");
		$o->objects_template('WiganRL::DataObject::Teamplayer',"$SITE_BASE_DIR/templates/Teamplayer.Row.AllMatches.html");
		my $c= WiganRL::DataObject::Competition->new;
		$c->data('COMPETITION_STATSTYPE',$cgi->param('COMPETITION_STATSTYPE'));
		$o->data('COMPETITION_STATSTYPE_OPTIONS',
			$c->get_field('COMPETITION_STATSTYPE_OPTIONS'));
		my $sg= WiganRL::DataObject::Statsgroup->new;
		$o->data('STATSGROUP_OPTIONS',
			$sg->get_field('STATSGROUP_OPTIONS'));
	}
	$o->related_template('WiganRL::DataObject::News',"$SITE_BASE_DIR/templates/News.Related.html");
	$o->related_template('WiganRL::DataObject::Matchstats',"$SITE_BASE_DIR/templates/Matchstats.Related.html");
	$o->related_template('WiganRL::DataObject::Image',"$SITE_BASE_DIR/templates/Image.Related.html");
	$o->related_template('WiganRL::DataObject::View',"$SITE_BASE_DIR/templates/View.Inline.html");
	$o->objects_template('WiganRL::DataObject::Image',"$SITE_BASE_DIR/templates/Image.Inline.html");

	$page->template('Page.Wide.html');
	$page->add_object($o);


##########################################################################################################################
# Statistics output pages
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Statistics(\.(\w+)\.(\w+)\.([\d]+)(\.(\w+))?)?/) {
	my $type= $2;  #squad or player
	my $by= $3;   # competition, referee etc
	my $id= $4;  #id   
	my $sortby= $6;

	if (!defined $1) {
		$type= 'SQUAD';
		$by= 'COMPETITION';
		my ($sth,$rv)= $dbh->get(['SQUAD','OBJECT','SEASON'],['PK_OBJECT_ID'],"",
		   "SEASON_ACTIVE='True' and SEASON.FK_OBJECT_ID=FK_SEASON_ID and
			SQUAD.FK_OBJECT_ID=PK_OBJECT_ID");
		if ($rv != 0) {
		   $id= ${$sth->fetchrow_arrayref};
		}
		$sth->finish;
	}
	if ($id) {
		if ($type eq 'SQUAD') {
			my $o= WiganRL::DataObject::Squad->new($id);
			$o->data('STATISTICS_TYPE',$by);
			$o->data('STATISTICS_SORTBY',$sortby);
			my $tname= $by;
			$tname=~ s/(\w+)/\u\L$1/g;  #title case
			$tname= "$SITE_BASE_DIR/templates/Squad.Stats.html";
			$page->add_object($o,$tname);
		} elsif ($type eq 'PLAYER') {
			my $o= WiganRL::DataObject::Player->new($id);
			$o->data('STATISTICS_TYPE',$by);
			$page->add_object($o,"Player.Statistics.html");
		}
	}
	$page->template('Page.Wide.html');

		

##########################################################################################################################
# Output object types
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^Object\.([\w]+)(\.(\w+))?/) {   #Object page
	my $type= $1;
	my $extarg= $3;
	
	#override ObjectID with extra arg
	# NOTE can't do this with Cached Offsite News stories because
	# in this case $extarg= 'cached'
	if ($extarg=~ /^\d+$/) {
		$cgi->param('ObjectID',$extarg);
	}
	
	$page->template("Page.Wide.html");
	my $o= WiganRL::DataObject->new_notype($cgi->param('ObjectID'));
   
	if (defined($o) && $o->loaded) {

		my $template= $type; 
		$template=~ s/(\w+)/\u\L$1/g;  #title case
		$o->template("$template.html");  #set default template
	
		$o->related_template('WiganRL::DataObject::News',"$SITE_BASE_DIR/templates/News.Related.html");
		$o->related_template('WiganRL::DataObject::Matchstats',"$SITE_BASE_DIR/templates/Matchstats.Related.html");
		$o->related_template('WiganRL::DataObject::Image',"$SITE_BASE_DIR/templates/Image.Related.html");
		$o->related_template('WiganRL::DataObject::Injury',"$SITE_BASE_DIR/templates/Injury.Related.html");
		$o->related_template('WiganRL::DataObject::Player',"$SITE_BASE_DIR/templates/Player.Related.html");
		$o->related_template('WiganRL::DataObject::Stadium',"$SITE_BASE_DIR/templates/Stadium.Related.html");
		$o->related_template('WiganRL::DataObject::Playersigning',"$SITE_BASE_DIR/templates/Playersigning.Related.html");
		$o->related_template('WiganRL::DataObject::View',"$SITE_BASE_DIR/templates/View.Inline.html");
		$o->related_template('WiganRL::DataObject::Vote',"$SITE_BASE_DIR/templates/Vote.Related.html");
		$o->related_template('WiganRL::DataObject::Usercolumn',"$SITE_BASE_DIR/templates/Usercolumn.Related.html");

		if ($type eq 'NEWS') {
			$page->template("Page.Normal.html");
		
			#$o->related_template('WiganRL::DataObject::Vote',"$SITE_BASE_DIR/templates/Vote.Inline.html");
			$o->objects_template('WiganRL::DataObject::Image',"$SITE_BASE_DIR/templates/Image.Inline.html");
			if ($o->loaded && $o->data('NEWS_OFFSITE') eq 'True' && $extarg ne 'Cached') {
				$o->template("News.Offsite.html");
			} else {
				$o->template("News.html");
			}
			$o->add_object(WiganRL::DataObject->new,"Search.News.html");
			
		} elsif ($type eq 'VIEW') {        
		
			my $list= WiganRL::DataObject->new;
			$list->template("View.Thread.html");
			#use view thread table
			my ($sth,$rv)= $dbh->get(['VIEW_THREAD'],['*'],"",
				"FK_HEAD_ID=".$o->data('FK_HEAD_ID'));
			my $vt= $sth->fetchrow_hashref;
			$sth->finish;

			my $lv_time= parseTime($cgi->cookie('WR_LAST_VISIT'));
			my $history= join(',',@{$session->history->{'ObjectID'}});

			my @pageids= split(',',$vt->{VT_PAGESTART_IDS});
			my $page;
			for ($page= 0; $page<$#pageids; $page++) {
				if ($pageids[$page] > $o->id) {
					$page= $page-1;
					last;
				} elsif ($pageids[$page] == $o->id) {
					last;
				}
			}
			my $n_per_page= 10;
			my $links= '';
			$links.= qq~<a href="javascript:getObject('~.$pageids[$page-1].qq~','VIEW');" 
						class="viewlink"><i>Prev</i></a>~ 
				if ($page > 0);
				
			for my $i (0..$#pageids) {
				$links.= ", " if ($links);
				$links.= qq~<a href="javascript:getObject('~.$pageids[$i].qq~','VIEW');" 
						class="viewlink">~ 
					if ($i != $page);
				$links.= ($i+1);
				$links.= "</a>";                
			}
			$links.= qq~, <a href="javascript:getObject('~.$pageids[$page+1].qq~','VIEW');" 
						class="viewlink"><i>Next</i></a>~ 
				if ($page < $#pageids);
			
			$list->data('VIEW_THREAD_PAGE_LINKS',$links);

			#TODO - record visited object history in a more efficient manner
			#add posts on this page
			my $oid= $cgi->param('ObjectID');
			for (split(',',$vt->{VT_POST_IDS})) {
				if ($_>=$pageids[$page] and 
					($page==$#pageids or $_<$pageids[$page+1])) {
					my $tmp= $o->new($_);
					$tmp->template("View.Thread.Inline.html");                    
					$list->add_object($tmp);

					### add to history
					$cgi->param('ObjectID',$_);
					$session->add_history;
				}
			}
			$cgi->param('ObjectID',$oid);

#			my $oid= $cgi->param('ObjectID');
#			for my $i (($page*$n_per_page)..($page*$n_per_page + $n_per_page-1)) {
#				if ($i <= $#$res) {
#					my $o= $$res[$i];
#					$o->template("View.Thread.Inline.html");                    
#					$list->add_object($o);
#					
#					### add to history
#					$cgi->param('ObjectID',$o->id);
#					$session->add_history;
#				}
#			}
#			$cgi->param('ObjectID',$oid);

			#get related info for bottom of list
			$o->template("View.Thread.Related.html");                    
			$o->related_template('WiganRL::DataObject::News',"$SITE_BASE_DIR/templates/News.Related.html");
			$o->related_template('WiganRL::DataObject::Matchstats',"$SITE_BASE_DIR/templates/Matchstats.Related.html");
			$o->related_template('WiganRL::DataObject::Image',"$SITE_BASE_DIR/templates/Image.Related.html");
			$o->related_template('WiganRL::DataObject::Injury',"$SITE_BASE_DIR/templates/Injury.Related.html");
			$o->related_template('WiganRL::DataObject::Player',"$SITE_BASE_DIR/templates/Player.Related.html");
			$o->related_template('WiganRL::DataObject::Stadium',"$SITE_BASE_DIR/templates/Stadium.Related.html");
			$o->related_template('WiganRL::DataObject::Playersigning',"$SITE_BASE_DIR/templates/Playersigning.Related.html");
			$o->related_template('WiganRL::DataObject::View',"$SITE_BASE_DIR/templates/View.Inline.html");
			$o->related_template('WiganRL::DataObject::Vote',"$SITE_BASE_DIR/templates/Vote.Related.html");
			$o->related_template('WiganRL::DataObject::Venue',"$SITE_BASE_DIR/templates/Venue.Related.html");

			my $h;
			if ($vt->{VT_HEAD_TYPE} eq 'VIEW') {
				$h= $o->new($vt->{FK_HEAD_ID});
			} else {  #if the head is a vote object
				$h= WiganRL::DataObject::Vote->new($vt->{FK_HEAD_ID});
				if (defined($h)) {
					if ($h->expired) {
						$o->objects_template('WiganRL::DataObject::Vote',"$SITE_BASE_DIR/templates/Vote.Inline.Results.html");
						$h->objects_template('WiganRL::DataObject::Voteoption',
							"$SITE_BASE_DIR/templates/Voteoption.Row.Results.html");
						$h->related_template('WiganRL::DataObject::News',"$SITE_BASE_DIR/templates/News.Related.html");
					} else {
						$o->objects_template('WiganRL::DataObject::Vote',"$SITE_BASE_DIR/templates/Vote.Inline.html");
						$h->objects_template('WiganRL::DataObject::Voteoption',
							"$SITE_BASE_DIR/templates/Voteoption.Row.Vote.html");
						$h->related_template('WiganRL::DataObject::News',"$SITE_BASE_DIR/templates/News.Related.html");
					}
				}
			}
			
			$list->data('VIEW_THREAD_RELATED_CONTENT',$o->output);
			$list->data('FK_VIEWFORUM_ID',$o->viewforum->id);
			$list->data('VIEWFORUM_VIEWFORUM_LINK_LIST',$o->viewforum->get_field('VIEWFORUM_LINK_LIST'));
			$list->data('VIEWFORUM_VIEWFORUM_NAME',$o->viewforum->get_field('VIEWFORUM_NAME'));
			$list->data('USER_VIEW_LOGIN_LINK',$user->get_field('USER_VIEW_LOGIN_LINK'));
			$o->template("View.Thread.Inline.html");
			$o->data('VIEW_THREAD',$list->output);
			
			
#			my $list= WiganRL::DataObject->new;
#			$list->template("View.Thread.Head.html");
#			for my $o (@$res) {
#				$o->template("View.Thread.Link.html");
#				my $id= $o->id;
##                if ($o->id == $cgi->param('ObjectID')) {
##                    $o->data('VIEW_HIGHLIGHT','highlight');
##                } elsif ((!defined $lv_time || parseTime($o->data('OBJECT_DATE')) > $lv_time) &&
##                    $history!~ /\,$id/) {
##                    $o->data('VIEW_HIGHLIGHT','highlightb');            
##                }
#				$list->add_object($o);            
#			}           
#			$o->data('VIEW_THREAD_LINKS',$list->output);
			$o->data('VIEW_THREAD_LINKS',$vt->{VT_LINKS_HTML});
			
			$o->template("View.html");
			if (defined($h) && $h->type eq 'VOTE') {  #if the head is a vote object
				if ($h->expired) {
					$o->objects_template('WiganRL::DataObject::Vote',"$SITE_BASE_DIR/templates/Vote.Inline.Results.html");
					$h->objects_template('WiganRL::DataObject::Voteoption',
						"$SITE_BASE_DIR/templates/Voteoption.Row.Results.html");
				} elsif ($user->loaded && $h->uservoted($user->id)) {
					$o->objects_template('WiganRL::DataObject::Vote',"$SITE_BASE_DIR/templates/Vote.Inline.Results.html");
					$o->data('USER_VOTED',qq~
						<div class="newsbody"><b>Voting Restricted:</b> You are restricted from voting as you have already cast your vote in this poll.</div>
						~);
					$h->objects_template('WiganRL::DataObject::Voteoption',
						"$SITE_BASE_DIR/templates/Voteoption.Row.Results.html");                
				} else {
					$o->objects_template('WiganRL::DataObject::Vote',"$SITE_BASE_DIR/templates/Vote.Inline.html");
					$h->objects_template('WiganRL::DataObject::Voteoption',
						"$SITE_BASE_DIR/templates/Voteoption.Row.Vote.html");
				}
			}        
			my $sbox= WiganRL::DataObject->new;
			$sbox->template("Search.View.html");
			$o->add_object($sbox);
	
		} elsif ($type eq 'VIEWFORUM') {
			$page->template("Page.Wide.html");
			$o->template("Viewforum.html");
			$o->objects_template('WiganRL::DataObject::View',"$SITE_BASE_DIR/templates/View.Link.html");

			my $sno= $cgi->param('StartID');

			#get cached field from object
			my $v= WiganRL::DataObject::View->new;
			$v->viewforum($o);

			my $objects= undef;
			if ($sno eq 'ALLREAD') {
				my $history= $session->history->{'ObjectID'};
				my $oid= $cgi->param('ObjectID');
				my @unread= $o->unread_content($history);
				for (@unread) {
					$cgi->param('ObjectID',$_->[0]);
					$session->add_history;
				}
				$cgi->param('ObjectID',$oid);
				$cgi->param('StartID','');
				$sno= 0;					
			} elsif ($sno eq 'ALLREADALLFORUMS') {
				my @now= localtime;
				my $now= sprintf("%04d%02d%02d%02d%02d%02d",$now[5]+1900,$now[4]+1,$now[3],$now[2],$now[1],$now[0]);
				$user->set_lastvisit($now);
				$sno= 0;
			}

			if ($sno) {
				$objects= $v->cacheVar("Views.List.OBJECTS.$sno");
			} else {
				$objects= $v->cacheVar('Views.List.OBJECTS');
			}
			$o->data('ADMIN_LINK_NEWTOPIC',$v->get_field('ADMIN_LINK_NEWTOPIC'));
			$o->data('OBJECTS',$objects);
			my $oarr= $v->objects;
			if (defined $oarr && $#$oarr>=0) {
				#last thread
				$o->data('NEW_THREAD_ID',$oarr->[0]->{Object}->id);
				$o->data('OLD_THREAD_ID',$oarr->[$#$oarr]->{Object}->id);    
			}

			my $sbox= WiganRL::DataObject->new;
			$sbox->template("Search.View.html");
			$o->add_object($sbox);

		} elsif ($type eq 'SQUAD') {
			$page->template("Page.Normal.html");
			$o->template("Squad.html");
			$o->objects_template('WiganRL::DataObject::Squadplayer',"$SITE_BASE_DIR/templates/Player.Snip.html");
			$o->objects_template('WiganRL::DataObject::Squadstaff',"$SITE_BASE_DIR/templates/Squadstaff.Snip.html");
			
			my $sbox= WiganRL::DataObject->new;
			$sbox->template("Search.Player.html");
			$o->add_object($sbox);
			
		} elsif ($type eq 'IMAGE') {
			$o->template("Image.html");
			
			my $sbox= WiganRL::DataObject->new;
			$sbox->template("Search.Image.html");
			$o->add_object($sbox);
			
		} elsif ($type eq 'SEASON') {
			$o->template("Season.html");
			$o->objects_template('WiganRL::DataObject::Competition',"$SITE_BASE_DIR/templates/Competition.Fixtures.Row.html");
			$o->objects_template('WiganRL::DataObject::Squad',"$SITE_BASE_DIR/templates/Squad.Snip.html");
			WiganRL::DataObject::Competition->objects_template('WiganRL::DataObject::Matchstats',"$SITE_BASE_DIR/templates/Matchstats.Fixtures.Row.html");
	
		} elsif ($type eq 'PLAYER') {
			$page->template('Page.Wide.html');
			$o->objects_template('WiganRL::DataObject::Image',"Image.Inline.html");
			$o->objects_template('WiganRL::DataObject::View',"View.Inline.html");
			$o->related_template('WiganRL::DataObject::View',"View.Inline.html");
			$o->template("Player.html");
	
			my $sbox= WiganRL::DataObject->new;
			$sbox->template("Search.Player.html");
			$o->add_object($sbox);
	
		} elsif ($type eq 'PLAYERSIGNING') {
			$o->template("Playersigning.html");
			WiganRL::DataObject::Ltable->objects_template('WiganRL::DataObject::Dltable',"$SITE_BASE_DIR/templates/Dltable.Row.html");
		} elsif ($type eq 'INJURY') {
			$o->template("Injury.html");
		} elsif ($type eq 'MATCHSTATS') {
			WiganRL::DataObject::Teamplayerscore->template("Teamplayerscore.String.html");
			WiganRL::DataObject::Teamplayer->template("Teamplayer.Row.html");
			WiganRL::DataObject::Squadplayer->template("Squadplayer.Matchstats.Row.html");
			WiganRL::DataObject::Userteamplayer->template("Userteamplayer.Matchstats.Row.html");
			$o->objects_template('WiganRL::DataObject::Image',"$SITE_BASE_DIR/templates/Image.Inline.html");
			$o->objects_template('WiganRL::DataObject::News',"$SITE_BASE_DIR/templates/News.Snip.html");
			if ($extarg eq 'Manofthematch') {
				$o->template("Matchstats.Manofthematch.html");     
				WiganRL::DataObject::Teamplayer->template("Teamplayer.Row.Manofthematch.html");
				WiganRL::DataObject::Teamplayerrating->template("Teamplayer.Row.Manofthematch.html");
			} elsif ($extarg eq 'Vote') {
				if ($user->loaded) {
					$o->team('HOME')->update_motm;
					$o->team('AWAY')->update_motm;
					$o->template("Matchstats.Manofthematch.Results.html");            
					WiganRL::DataObject::Teamplayer->template("Teamplayer.Row.Manofthematch.Results.html");            
				} else {
					$o->template("Admin.Denied.html");
				}
			} elsif ($extarg eq 'Results') {
				$o->template("Matchstats.Manofthematch.Results.html");            
				WiganRL::DataObject::Teamplayer->template("Teamplayer.Row.Manofthematch.Results.html");            
			} elsif ($o->preview) {
				$o->objects_template('WiganRL::DataObject::News',"$SITE_BASE_DIR/templates/News.Related.html");
				$o->related_template('WiganRL::DataObject::View',"$SITE_BASE_DIR/templates/View.Related.html");
				WiganRL::DataObject::Squadplayer->related_template('WiganRL::DataObject::Injury',"$SITE_BASE_DIR/templates/Injury.Related.html");
				WiganRL::DataObject::Squadplayer->template("Squadplayer.Matchstats.Row.html");
				$o->template("Matchstats.Preview.html");
			} else {
				$o->template("Matchstats.html");
			}

		} elsif ($type eq 'STADIUM') {
			$o->objects_template('WiganRL::DataObject::Venue',"$SITE_BASE_DIR/templates/Venue.Snip.html");
			$o->related_template('WiganRL::DataObject::Venue',"$SITE_BASE_DIR/templates/Venue.Snip.html");
			$o->template("Stadium.html");
		} elsif ($type eq 'VENUE') {
			$o->template("Venue.html");
		} elsif ($type eq 'DLTABLE' || $type eq 'LTABLE') {
			if ($type eq 'LTABLE') {  #get latest dltable for this ltable
				my $s= WiganRL::Search->new;
				$s->clear; $s->table('DLTABLE'); $s->where('FK_LTABLE_ID='.$o->id);
				$s->orderby('DLTABLE_DATE desc');
				my $res= $s->search;
				if ($#$res >= 0) {
					$o= $res->[0];
				}
			}
			$o->template("Dltable.html");
			$o->objects_template('WiganRL::DataObject::Ltablerow',"$SITE_BASE_DIR/templates/Ltablerow.html");
			WiganRL::DataObject::Ltable->objects_template('WiganRL::DataObject::Dltable',"$SITE_BASE_DIR/templates/Dltable.Row.html");
		} elsif ($type eq 'USER') {
			$o->template("User.html");
			WiganRL::DataObject::Ltable->objects_template('WiganRL::DataObject::Dltable',"$SITE_BASE_DIR/templates/Dltable.Row.html");
		} elsif ($type eq 'VOTE') {
			if ($extarg eq 'Vote') {  #bypass permissions for voting
				if ($user->loaded) {  #all users can vote
					$o->update;
					$o->template("Vote.Results.html");
					$o->objects_template('WiganRL::DataObject::Voteoption',"$SITE_BASE_DIR/templates/Voteoption.Row.Results.html");
				} else {
					$o->template("Admin.Denied.html");
				}
			} elsif ($extarg eq 'Results' || $o->expired) {
				$o->template("Vote.Results.html");
				$o->objects_template('WiganRL::DataObject::Voteoption',"$SITE_BASE_DIR/templates/Voteoption.Row.Results.html");
			} elsif ($user->loaded && $o->uservoted($user->id)) {
				$o->template("Vote.Results.html");
				$o->data('USER_VOTED',qq~
					<div class="newsbody"><b>Voting Restricted:</b> You are restricted from voting as you have already cast your vote in this poll.</div>
						~);
				$o->objects_template('WiganRL::DataObject::Voteoption',"$SITE_BASE_DIR/templates/Voteoption.Row.Results.html");            
			} else {
				$o->objects_template('WiganRL::DataObject::Voteoption',"$SITE_BASE_DIR/templates/Voteoption.Row.Vote.html");
			}
		} elsif ($type eq 'USERFAVTEAM') {
			$page->template("Page.Normal.html");
			$o->template("Userfavteam.html");
#            $o->objects_template('WiganRL::DataObject::Userfavteamplayer',"$SITE_BASE_DIR/templates/Userfavteamplayer.Row.Edit.html");
			WiganRL::DataObject::Userfavteamplayer->template("Userfavteamplayer.Row.html");
		} elsif ($type eq 'USERTEAM') {
			$page->template("Page.Wide.html");
			$o->template("Userteam.html");
			WiganRL::DataObject::Userteamplayer->template("Userteamplayer.Row.html");
		} elsif ($type eq 'AVITEM') {
			$page->template("Page.Normal.html");
			$o->template("AVItem.html");
		}
		$o->inc_nviews;
		$page->add_object($o);
	}


##########################################################################################################################
##########################################################################################################################
# User statuses
##########################################################################################################################

} elsif ($cgi->param('status')=~ /^User\.Details(?:\.([\w]+))?(?:\.([\w]+))?/) {   #editable details
	my $action= $1 ? $1 : '';
	my $action2= $2 ? $2 : '';
	my $o= WiganRL::DataObject->new;
	$o->template("User.ControlPanel.html");

	if ($action eq 'Update' || $action2 eq 'Update') {
		$user= $user->update;
	}

	if ($action eq "Style") {
		$user->template("User.Details.Style.html");
	} elsif ($action eq "Messages") {
		$user->template("User.Details.Messages.html");
	} elsif ($action eq "Updates") {
		$user->template("User.Details.Updates.html");
	} else {
		$user->template("User.Details.html");
	}
	$o->add_object($user);
	$page->add_object($o);

} elsif ($cgi->param('status')=~ /^User\.Userfavteams(\.([\w]+))?/) {   #sign up for content updates
	my $action= $2 ? $2 : '';
	my $o= WiganRL::DataObject->new;
	$o->template("User.ControlPanel.html");

	$user->data('ADMIN_LINK_USERFAVTEAM',WiganRL::DataObject::Userfavteam->new()->get_field('ADMIN_LINK_USERFAVTEAM'));
	$user->objects_template('WiganRL::DataObject::Userfavteam',"Userfavteam.Snip.html");
	$user->template("User.Userfavteams.html");
	$o->add_object($user);
	$page->add_object($o);

} elsif ($cgi->param('status')=~ /^User\.Showuserfavteams(\.([\w]+))?/) {   #sign up for content updates
	my $action= $2 ? $2 : '';
	my $o= WiganRL::DataObject::User->new($cgi->param('FK_USER_ID'));
	$o->template("User.Showuserfavteams.html");
	$page->add_object($o);
	$o->objects_template('WiganRL::DataObject::Userfavteam',"Userfavteam.Snip.html");


##########################################################################################################################
# Other User statuses
##########################################################################################################################

} elsif ($cgi->param('status')=~ /^User\.Online\.List(\.([\w]+))?/) {  #list online users
	my $list= WiganRL::DataObject->new;
	$list->template("User.Online.List.html");

	my ($sth,$rv)= $dbh->get(['SESSION'],['SESSION_DATA'],"",
	   "SESSION_ACTIVE='True' and SESSION_TIME > (NOW() - INTERVAL 10 MINUTE)");
	my %users;
	for (@{$sth->fetchall_arrayref}) {
		if ($_->[0]=~ /UserID=(\d+)/) {
			$users{$1}= 1;
		}
	}
	$sth->finish;
	my $users= '';
	my @keys= keys %users;
	for (@keys) {
	   my $o= WiganRL::DataObject::User->new($_);
	   $o->template("User.Snip.html");
	   $list->add_object($o);
	}
	
	$list->data('USERS_ONLINE',$#keys+1);   
	$page->add_object($list);


##########################################################################################################################
##########################################################################################################################
# Login/Logoff and registration statuses
##########################################################################################################################

} elsif ($cgi->param('status')=~ /^Site\.Login(\.(.*))?/) {   #Login page
	my $action= $2;
	$action= '' unless defined($action);
	
	if ($action eq 'Login') {  #Login
		# login user
		$user= $user->login($cgi->param('USER_NAME'),$cgi->param('USER_PASSWORD'));
		
		##########################################################################################################################
		# log users ip if required
		##########################################################################################################################
		if ($user->loaded and $user->data('USER_LOGIPS') eq 'True') {
			my $uip= WiganRL::DataObject::Userip->new;
			$uip->linkeduser($user);
			$uip->update;
		}

		if (!$user->loaded || $user->id eq '') {#invalid login
			$cgi->cookie('WR_USER_LOGIN','');
			my $o= WiganRL::DataObject->new();
			$o->template("Site.Login.Error.html");
			$page->add_object($o);
		} elsif ($user->data('USER_ACTIVE') ne 'True') {#inactive user
			$cgi->cookie('WR_USER_LOGIN','');
			my $o= WiganRL::DataObject->new();
			$o->template("Site.Login.Inactive.html");
			$page->add_object($o);
		} else {
			if ($cgi->param('next_status') eq '') {
				$cgi->param('next_status','Home');
			}
				#update session
			$cgi->param('UserID',$user->id);
			$session->from_cgi;
			$session->update;
			$cgi->delete('UserID');

				#remember user login details if required
			my @cookies= ($session_cookie);
			if ($cgi->param('USER_LOGIN') eq 'true') {
				push @cookies,$cgi->cookie(
					-name=>'WR_USER_LOGIN',
					-value=> $session->encrypt($session->encrypt($cgi->param('USER_NAME')).
							','.
						$session->encrypt($cgi->param('USER_PASSWORD'))),
					-expires=>'+1M');
			}
			
			print $cgi->redirect(
				-uri=>"$CGI_BASE_URL/wiganrl?status=".$cgi->param('next_status')."\&ObjectID=".$cgi->param('ObjectID').
					$cgi->param('SessionLink'),
				-nph=>0,
				-cookie=>\@cookies);   #non-parsed header
			return;
		}
	} else {  #output login page
		my $o= WiganRL::DataObject->new();
		$o->template("Site.Login.html");
		$page->add_object($o);		
	}

} elsif ($cgi->param('status')=~ /^Site\.Logoff/) {

	#set last visit date
	my @now= localtime;
	my $now= sprintf("%04d%02d%02d%02d%02d%02d",$now[5]+1900,$now[4]+1,$now[3],$now[2],$now[1],$now[0]);
	my $u= WiganRL::DataObject::User->new($session->data('UserID'));
	$u->set_lastvisit($now);

	#end session and throw user away
	$cgi->delete('UserID');
	#$user->loaded(0);
	$session->from_cgi;
	$session->update;
	$session->logoff;
	

	my $o= WiganRL::DataObject->new();
	$o->template("Site.Logoff.html");
	$page->add_object($o);


} elsif ($cgi->param('status')=~ /^Site\.Register\.Confirm/) {
	my $o= WiganRL::DataObject->new();
	$user->load($cgi->param('ObjectID'));
	if ($user->loaded) {
		$user->activate();
		$o->data('FORWARD_URL',$SITE_BASE_URL);
		$o->data('USER_NAME',$user->data('USER_NAME'));
		$o->data('USER_PASSWORD',$user->data('USER_PASSWORD'));
		$o->template("Site.Register.Confirm.html");
		$user->loaded(0);
	} else {
		$o->data('FORWARD_URL',$SITE_BASE_URL);
		$o->template("Site.Register.Confirm.Error.html");
	}    
	
	$page->add_object($o);


} elsif ($cgi->param('status')=~ /^Site\.Register/) {

	$user->template("Site.Register.Details.html");
	if ($cgi->param('REGISTER_STATE') && $cgi->param('REGISTER_STATE') eq 'Register') {
		
		#insert user and output confirmation page if sucessfull
		$user= $user->register;
		if ($user->update_status > 0) {
			if (1 || $SEND_EMAILS) {
				$user->data('USER_CONFIRM_URL',
					"http://www.wigan-warriors.com/cgi-bin/wigan?status=Site.Register.Confirm\&ObjectID=".$user->id);
				$cgi->param('ObjectID',$user->id);
				$user->sendemail("$EMAIL_BASE_DIR/User.Confirm.txt",$cgi->param('USER_NAME'),$cgi->param('USER_EMAIL'),
					'"Wigan-Warriors.com" <webmaster@wigan-warriors.com>');
			}
			$user->loaded(0);
			$user->template("Site.Register.Sent.html");
		}
	}
	$page->add_object($user);



##########################################################################################################################
##########################################################################################################################
# Admin statuses 
##########################################################################################################################

} elsif ($cgi->param('status')=~ /^Admin/) {   #Admin page
	$page->template("Page.Wide.html");
	
	   
	if ($cgi->param('status')=~ /^Admin\.Home$/) {  #admin user home page
		my $o= WiganRL::DataObject->new();
		$o->template("Admin.Home.html");
		$page->add_object($o);
	
	

#    } elsif ($cgi->param('status')=~ /^Admin\.Objects\.List(\.(.*?))?$/) {  #all object types
#
#        my $s= WiganRL::Search->new;
#        my $o= WiganRL::DataObject->new;
#        $o->template("Admin.Object.List.html");
#        for (@types) {
#            $s->clear; $s->table($_); $s->search;
#            $s->results->[0]->template("Admin.Object.Type.Row.html");
#            $s->results->[0]->data('OBJECT_TYPE_COUNT',$#{$s->results}+1);
#            $o->add_object($s->results->[0]);
#        }
#        $page->add_object($o);


	} elsif ($cgi->param('status')=~ /^Admin\.List\.([\w]+)(\.(.*?))?$/) {  #list objects of specific type
		my $type= $1;
		my $s= WiganRL::Search->new;
		my $o= WiganRL::DataObject->new;
		$o->template("Admin.Object.Type.List.html");
		$s->clear; $s->table($type); $s->search;
		my $res= $s->results;
		for (@$res) {
			$_->template("Admin.Object.Row.html");
			$o->add_object($_);
		}
		$page->add_object($o);


	### User Content    
	} elsif ($cgi->param('status')=~ /^Admin\.Page(\.(.*?))?$/) {  #edit user content on page
		my $action= $2 ? $2 : '';
		if ($user->permission('USER_CONTENT',$ACTION_EDIT)) {
			my ($uc)= WiganRL::DataObject::UserContent->new($cgi->param('USERCONTENT_TYPE'));
			
			if ($action eq 'Update') {  #update user content
				#print "<pre>Action: $action: Updating..</pre>";
				$uc->update($cgi);
			}
			$uc->template("UserContent.Edit.html");
			$page->add_object($uc);
			
			
		} else {
			my $o= WiganRL::DataObject->new();
			$o->template("Admin.Denied.html");
			$page->add_object($o);
		}    
##########################################################################################################################
# Admin Edit Object
##########################################################################################################################

	} elsif ($cgi->param('status')=~ /^Admin\.Edit\.Object\.([\w]+)(?:\.(.*?))?$/) {  #edit object
		my $type= $1;
		my $action= defined $2 ? $2 : '';
		my $tname= Diva::DataObject->_content_classes->{Diva::DataObject->_content_types->{$type}};
		if ($type eq 'Newsoffsite') {
			$tname= 'WiganRL::DataObject::News';        
		}
		my $template= $tname;
		$template=~ s/^.*\:([^\:]*$)/$1/g;
		my $o= $tname->new($cgi->param('ObjectID'));

		my $email_template= '';
		if ($type eq 'NEWS') {
			$email_template= 'News.Edit.txt';
		} elsif ($type eq 'NEWSoffsite') {
			$email_template= 'News.Edit.txt';
		} elsif ($type eq 'VIEW') {
			if ($cgi->param('ParentID') ne '') {
				my $p= $o->new_notype($cgi->param('ParentID'));
				if (defined($p) && $p->type eq 'VIEW') {
				#    $p->template("View.Replyto.html");
				#    $o->add_object($p);
					my $pre= '';
					$pre= 'Re: ' if ($p->get_field($p->title_field)!~ /^Re\:/);
					$o->data('VIEW_TITLE',$pre.$p->get_field($p->title_field));
				} elsif (defined($p) && !$o->loaded) {
					my $type= $p->type;
					$type=~ s/(\w+)/\u\L$1/g;  #title case  
					my $pre= '';
					$pre= 'Re: ' if ($p->get_field($p->title_field)!~ /^Re\:/);                              
					$o->data('VIEW_TITLE',$pre.$p->get_field($p->title_field));
					$cgi->param('HeadID',$p->id);
				}
			}
			$email_template= 'View.Edit.txt';
			WiganRL::DataObject::View->related_template('WiganRL::DataObject::News',"News.Related.Checkbox.html");
			WiganRL::DataObject::View->related_template('WiganRL::DataObject::Matchstats',"Matchstats.Related.Checkbox.html");
		} elsif ($type eq 'IMAGE') {
			$email_template= 'Image.Edit.txt';
		} elsif ($type eq 'SQUAD') {
			if (!$o->loaded) {
				$o->data('FK_CLUB_ID',$cgi->param('ParentID'));
				$o->data('FK_SEASON_ID',getSeason()->id);
			}
		} elsif ($type eq 'USERFAVTEAM') {
			if (!$o->loaded) {
				#load appropriate team if required
				if ($cgi->param('USERFAVTEAM_SEASON') > 0) {
					my $s= WiganRL::Search->new; $s->table('USERFAVTEAM'); 
					$s->where("FK_USER_ID = ".$user->id." and FK_SEASON_ID='".$cgi->param('USERFAVTEAM_SEASON')."'");
					my $res= $s->search;
					if ($#$res >= 0) {
						$o= $res->[0];
					} else {                    
						$o->data('FK_SEASON_ID',$cgi->param('USERFAVTEAM_SEASON'));
					}
				} else {
					my $s= WiganRL::Search->new; $s->table('USERFAVTEAM'); 
					$s->where("FK_USER_ID = ".$user->id." and USERFAVTEAM_TYPE='Alltime'");
					my $res= $s->search;
					if ($#$res >= 0) {
						$o= $res->[0];
					}                
				}
			}
		} elsif ($type eq 'USERTEAM') {
			if (!$o->loaded) {
				#load appropriate match if required
				if ($cgi->param('ParentID') > 0) {
					my $s= WiganRL::Search->new; $s->table('USERTEAM'); 
					$s->where("FK_USER_ID = ".$user->id." and FK_MATCHSTATS_ID=".$cgi->param('ParentID'));
					my $res= $s->search;
					if ($#$res >= 0) {
						$o= $res->[0];
					} else {
						$o->matchstats(WiganRL::DataObject::Matchstats->new($cgi->param('ParentID')));
					}
				}
			}
		} elsif ($type eq 'USER') {
			WiganRL::DataObject::Userip->template('Userip.Row.html');
		}            

		if (defined($o) && (($o->loaded && $o->permission($ACTION_EDIT))
				|| (!$o->loaded && $o->permission($ACTION_INSERT))) ) {
			if ($action eq 'Update') {  #update
				my $loaded= $o->loaded;
				#carp "Updating: $o";
				$o= $o->update($cgi);
				$o->update_related;       
				if ($o->update_status) {  # sucessful update                    
					#now send email notification
					
					if ($email_template ne '' && $SEND_EMAILS && !$loaded) {  #only send for new objects
						#send to administrator
						$o->sendemail("$EMAIL_BASE_DIR/$email_template",$ADMIN_NAME,$ADMIN_EMAIL);
					}

					if ($email_template ne '' && !$loaded) {  #only send for new objects
						#send to all users that have requested it.
						my $s= WiganRL::Search->new;
						$s->table('USER'); $s->where("USER_UPDATES = 'Imediate'");
						my $users= $s->search;

						#Add users that are watching this thread
						if ($o->type eq 'VIEW') {
							$s->clear;
							$s->table('VIEWWATCH'); 
							$s->where("VIEWWATCH.FK_HEAD_ID = ".$o->data('FK_HEAD_ID')." and ".
								"VIEWWATCH_SENDEMAIL = 'True'");
							my $res= $s->search;
							for (@$res) {
								$_->data('WATCHED_USER','True');
								push @$users,$_->owner;
							}
						}
						
						my $email= WiganRL::DataObject->new;
						my $sid= $cgi->param('SessionID');
						$cgi->param('CGI_BASE_URL',"http://www.wigan-warriors.com/cgi-bin/wigan");
						$cgi->param('SessionID','');
						$email->add_object($o);
						$email->data('SITE_BASE_URL',$SITE_BASE_URL);
						$email->data('STYLE','2003home');
						
						#add menus
						my $o2= WiganRL::DataObject->new();
						$o2->template("Site.Menu.html");
						$email->data("SITE_MENU",$o2->output);
						
						#add heading
						$o2->template("Site.Title.html");
						$email->data("SITE_TITLE",$o2->output);
						
						#add copyright
						$o2->template("Site.Copyright.html");
						$email->data("SITE_COPYRIGHT",$o2->output);
						my $t= $o->template;  #remember template
						for (@$users) {
							if ($_->data('WATCHED_USER') ne 'True') {
								if ($_->data('USER_EMAILTYPE') eq 'HTML') {
									$o->template("$EMAIL_BASE_DIR/$template.Snip.html");
									$email->sendemail("$EMAIL_BASE_DIR/User.Update.html",$_->data('USER_NAME'),$_->data('USER_EMAIL'));
								} else {
									$o->template("$EMAIL_BASE_DIR/$template.Snip.txt");
									$email->sendemail("$EMAIL_BASE_DIR/User.Update.txt",$_->data('USER_NAME'),$_->data('USER_EMAIL'));
								}
							} else {
								if ($_->data('USER_EMAILTYPE') eq 'HTML') {
									$o->template("$EMAIL_BASE_DIR/$template.Snip.html");
									$email->sendemail("$EMAIL_BASE_DIR/User.ViewWatch.html",$_->data('USER_NAME'),$_->data('USER_EMAIL'));
								} else {
									$o->template("$EMAIL_BASE_DIR/$template.Snip.txt");
									$email->sendemail("$EMAIL_BASE_DIR/User.ViewWatch.txt",$_->data('USER_NAME'),$_->data('USER_EMAIL'));
								}
							}
						}
						$o->template($t);
						$cgi->param('SessionID',$sid);
						$cgi->param('CGI_BASE_URL',$CGI_BASE_URL);
					}
					
					#now redirect if required
					if ($cgi->param('next_status') ne '') {
						my $oid= $o->id;
						if ($cgi->param('next_status')=~ /\.(\d+)/) {
							$oid= $1;
						}
						print $cgi->redirect(
							-uri=>"$CGI_BASE_URL/wiganrl?status=".$cgi->param('next_status').
								"\&ObjectID=".$oid.$cgi->param('SessionLink'),
							-nph=>0);   #non-parsed header
					}

				}
			} elsif ($action eq 'Activate') {  #activate
				if ($type eq 'SEASON') {  #set one active season
					$o->dbh->update('SEASON',['SEASON_ACTIVE'],['False']);
					$o->dbh->update('SEASON',['SEASON_ACTIVE'],['True'],"FK_OBJECT_ID=".$o->id);
				}
			} elsif ($action eq 'GetURL') {  #update from url
				if ($type eq 'DLTABLE') {  #only for DLTABLES
					my $p= $o->new_notype($cgi->param('FK_LTABLE_ID'));  #get parent table
					my $name= $p->get_field('COMPETITION_COMPETITION_NAME');
					#carp "Name: $name";
					if ($name=~ /Super League/) {
						$o->updatefromurl('Super League');
					} elsif ($name=~ /Senior Academy/) {
						$o->updatefromurl('Senior Academy');
					} elsif ($name=~ /Junior Academy/) {
						$o->updatefromurl('Junior Academy');
					}
				}
			}

			#setup output templates
			#add extra user options based on permissions
			if ($o->loaded) {
				if ($user->userpermission($o->type,$o->id,$USERPERM_MODERATOR) &&
						-e "$SITE_BASE_DIR/templates/$template.Moderator.html") {
					$o->template("$template.Moderator.html");
					$o->data('OBJECT_MODERATOR_HTML',$o->output);
				}
				if ($user->userpermission($o->type,$o->id,$USERPERM_ADMIN) &&
						-e "$SITE_BASE_DIR/templates/$template.Administrator.html") {
					$o->template("$template.Administrator.html");
					$o->data('OBJECT_ADMIN_HTML',$o->output);
				}
				if ($user->userpermission($o->type,$o->id,$USERPERM_SUPERADMIN) &&
						-e "$SITE_BASE_DIR/templates/$template.SuperAdministrator.html") {
					$o->template("$template.SuperAdmin.html");
					$o->data('OBJECT_SUPERADMIN_HTML',$o->output);
				}
			}
			$o->template("$template.Edit.html");
					
			if ($type eq 'NEWS') {
				#if ($o->loaded && $o->data('NEWS_OFFSITE') eq 'True') {
				#    $o->template("News.Offsite.Edit.html");            
				#}
			} elsif ($type eq 'NEWSoffsite') {
				$o->data('NEWS_OFFSITE','True') if (!$o->loaded);
				$o->template("News.Offsite.Edit.html");            
			} elsif ($type eq 'VIEW') {
				if ($cgi->param('ParentID') ne '') {
					my $p= $o->new_notype($cgi->param('ParentID'));
					if (defined($p) && $p->type eq 'VIEW') {
						$p->template("View.Replyto.html");
						$o->add_object($p);
					} elsif (defined($p) && !$o->loaded) {
						my $type= $p->type;
						$type=~ s/(\w+)/\u\L$1/g;  #title case            
						$o->data('VIEW_TITLE','Re: '.$p->get_field($p->title_field));
						$cgi->param('HeadID',$p->id);
					}
				}
			} elsif ($type eq 'SEASON') {
				$o->objects_template('WiganRL::DataObject::Competition',"$SITE_BASE_DIR/templates/Competition.Fixtures.Row.Edit.html");
				WiganRL::DataObject::Competition->objects_template('WiganRL::DataObject::Matchstats',"$SITE_BASE_DIR/templates/Matchstats.Fixtures.Row.Edit.html");
			} elsif ($type eq 'COMPETITION') {
				$o->objects_template('WiganRL::DataObject::Matchstats',"$SITE_BASE_DIR/templates/Matchstats.Fixtures.Row.Edit.html");
				$o->objects_template('WiganRL::DataObject::Ltable',"$SITE_BASE_DIR/templates/Ltable.Row.Edit.html");
			} elsif ($type eq 'MATCHSTATS') {
				WiganRL::DataObject::Teamplayerscore->template("Teamplayerscore.String.Edit.html");
				WiganRL::DataObject::Teamplayer->template("Teamplayer.Row.Edit.html");
			} elsif ($type eq 'PLAYER') {
				$o->objects_template('WiganRL::DataObject::Playersigning',"Playersigning.Snip.Row.html");
				$o->objects_template('WiganRL::DataObject::Squadplayer',"Squadplayer.Player.Row.html");
				$o->objects_template('WiganRL::DataObject::Injury',"Injury.Row.Edit.html");
				$o->objects_template('WiganRL::DataObject::Playerfixedstats',"Playerfixedstats.Row.Edit.html");
			} elsif ($type eq 'SQUAD') {
				$o->objects_template('WiganRL::DataObject::Squadplayer',"Squadplayer.Row.Edit.html");
				$o->objects_template('WiganRL::DataObject::Squadstaff',"Squadstaff.Row.Edit.html");
			} elsif ($type eq 'LTABLE') {
				$o->objects_template('WiganRL::DataObject::Dltable',"$SITE_BASE_DIR/templates/Dltable.Row.Edit.html");
			} elsif ($type eq 'DLTABLE') {
				$o->objects_template('WiganRL::DataObject::Ltablerow',"$SITE_BASE_DIR/templates/Ltablerow.Edit.html");
			} elsif ($type eq 'CLUB') {
				$o->objects_template('WiganRL::DataObject::Clubname',"$SITE_BASE_DIR/templates/Clubname.Row.html");
			} elsif ($type eq 'USERFAVTEAM') {
				WiganRL::DataObject::Userfavteamplayer->template("Userfavteamplayer.Row.Edit.html");
			} elsif ($type eq 'USERTEAM') {
				WiganRL::DataObject::Userteamplayer->template("Userteamplayer.Row.Edit.html");
			} elsif ($type eq 'PLAYERFIXEDSTATS') {
				$o->objects_template('WiganRL::DataObject::Playerfixedstatsscore',"Playerfixedstatsscore.Row.Edit.html");
			} elsif ($type eq 'USER') {
				WiganRL::DataObject::Userip->template("Userip.Row.html");
			}            

			$page->add_object($o);
		} else {
			$o= WiganRL::DataObject->new();
			$o->template("Admin.Denied.html");
			$page->add_object($o);
		}        
##########################################################################################################################
# Admin Delete Object
##########################################################################################################################

	} elsif ($cgi->param('status')=~ /^Admin\.Delete\.Object\.([\w]+)(\.(.*?))?$/) {  #delete object
		my $type= $1;
		my $action= defined $3 ? $3 : '';
		my $tname= $type;  
		my $o= WiganRL::DataObject->new_notype($cgi->param('ObjectID'));

		if (defined($o) && ($o->type eq $type) && ($o->loaded && $o->permission($ACTION_DELETE)) ) {
			if ($o->type eq 'VIEW') {
				$cgi->param('HeadID',$o->data('FK_HEAD_ID'));
			}
			$o->template("Admin.Object.Deleted.html");
			$page->add_object($o);
			$o= $o->dbdelete($cgi);

			#now redirect if required
			if ($cgi->param('next_status') ne '') {
				my $oid= $o->id;
				if ($cgi->param('next_status')=~ /\.(\d+)/) {
					$oid= $1;
				}
				print $cgi->redirect(
					-uri=>"$CGI_BASE_URL/wiganrl?status=".$cgi->param('next_status').
						"\&ObjectID=".$oid.$cgi->param('SessionLink'),
					-nph=>0);   #non-parsed header
			}

		} else {
			$o= WiganRL::DataObject->new();
			$o->template("Admin.Denied.html");
			$page->add_object($o);
		}        
	}    

##########################################################################################################################
# Search Engine Links
##########################################################################################################################
} elsif ($cgi->param('status')=~ /^searchengine$/) {    #search engine links page
	$page->template("Page.Blank.html");
	
	my $dbh= WiganRL::DataObject->dbh();
	my $o= WiganRL::DataObject->new();
	$o->template("Searchengine.Links.html");
	my ($sth,$rv)= $dbh->get(['OBJECT','CONTENT_TYPE'],['PK_OBJECT_ID','CONTENTTYPE_NAME'],'',
		"FK_CONTENTTYPE_ID = PK_CONTENTTYPE_ID and OBJECT_LINKABLE='True'");
	my $output= '';
	for (@{$sth->fetchall_arrayref}) {
		$output.= qq~<a href="$CGI_BASE_URL?ObjectID=$_->[0]\&status=Object.$_->[1]"
			class="searchengine">Link</a> ~;
	}
	$sth->finish;
	$o->data('SEARCHENGINE_LINKS',$output);
	
	$page->add_object($o);
}

#already loaded above
#$uc= WiganRL::DataObject::UserContent->new($cgi->param('status'));
$uc->template("UserContent.Footer.html");
$page->add_object($uc);

print $page->output(); 


#maintainence operations after page delivery



##########################################################################################################################
# update session
##########################################################################################################################

#$session->update;

# switch maintenence operations on status
if ($cgi->param('status')=~ /^Admin\.Edit\.Object\.([\w]+)(\.(.*?))?$/) {  #edit object

	my $type= $1;
	my $action= $3;
	my $o= WiganRL::DataObject->new_notype($cgi->param('ObjectID'));
	if (defined $o && (($o->loaded && $o->permission($ACTION_EDIT))
			|| (!$o->loaded && $o->permission($ACTION_INSERT))) ) {
		if ($action eq 'Update') {  #update
			# auto-related objects updating code
			if ($type eq 'NEWS') {
				#WiganRL::DataObject::Player->auto_related($o);
				WiganRL::DataObject::Image->auto_related($o,'norecip');                
				WiganRL::DataObject::Player->auto_links($o);
			} elsif ($type eq 'PLAYER') {
				$o->update_related;
				WiganRL::DataObject::Image->auto_related($o);                
				WiganRL::DataObject::Player->auto_links($o);
			} elsif ($type eq 'IMAGE') {
				WiganRL::DataObject::Player->auto_links($o);
				$o->auto_related("WiganRL::DataObject::Player");
			} elsif ($type eq 'VIEW') {
				WiganRL::DataObject::View->new->cacheVar('Views.List.OBJECTS',1);
			}
			WiganRL::Search->update_latest($type);
		}
		$o->finish;
	}        
} elsif ($cgi->param('status')=~ /^Admin\.Delete\.Object\.([\w]+)(\.(.*?))?$/) {  #delete object
	my $type= $1;
	if ($type eq 'VIEW') {
		my $o= WiganRL::DataObject::View->new;
		$o->cacheVar('Views.List.OBJECTS',1);
		$o->data('FK_HEAD_ID',$cgi->param('HeadID'));
		$o->update_thread;
	}
	WiganRL::Search->update_latest($type);
}


##########################################################################################################################
# garbage collect
##########################################################################################################################

$session->garbage_collect;
WiganRL::DataObject->garbage_collect;
$page->finish;
WiganRL::DataObject->search->garbage_collect;

   $dbh->disconnect;
#	return OK;
	return 1;
}

#sub sendemail {
#    my $script= 'c:/wwcom/v2.0/cgi-bin/sendmail.pl';
#    my ($template,$to,$email,$cgi)= @_;
#    
#    my $args= "USER_NAME=$to\&USER_EMAIL=$email";
#    for ($cgi->param) {
#        $args.= '&'.$_.'='.escape($cgi->param($_));
#    }
#    open(MAIL,qq~$script $template "$args" |~);
#    my @out= <MAIL>;
#    close(MAIL);
#
#    return (@out);
#}

sub getSeason {
	my $sid= shift;
	if (!$sid) {
		my $s= WiganRL::DataObject->search;   
		$s->clear; $s->table('SEASON');
		$s->where("SEASON_ACTIVE='True'");
		return $s->search(1)->[0];
	} else {
		return WiganRL::DataObject::Season->new($sid);    
	}
}

sub getSquad {
	my $sid= shift;
	if (!$sid) {
		my $season= getSeason();
		my $s= WiganRL::DataObject->search;   
		$s->clear; $s->table('SQUAD');
		$s->where("FK_CLUB_ID=$CLUB_ID and FK_SEASON_ID='".$season->id."'");
		$s->orderby("SQUAD_ORDER");
		return $s->search(1)->[0];
	} else {
		return WiganRL::DataObject::Squad->new($sid);
	}
}

sub parseTime {
	my $tstr= shift;
	if (!defined $tstr) {
		return undef;
	}
	if ($tstr=~ /\w+\,\s*(\d+)\s*(\w+)\s*(\d{4})\s*(\d{2})\:(\d{2})\:(\d{2})/) {
		my $mhash= {'Jan' => 0, 'Feb' => 1, 'Mar' => 2, 'Apr' => 3, 'May' => 4, 'Jun' => 5, 'Jul' => 6,
			'Aug' => 7, 'Sep' => 8, 'Oct' => 9, 'Nov' => 10, 'Dec' => 11};
		return timelocal($6,$5,$4,$1,$mhash->{$2},$3);
	} elsif ($tstr=~ /(\d+)\-(\d+)\-(\d+) (\d+)\:(\d+)\:(\d+)/) {
		return timelocal($6,$5,$4,$3,$2-1,$1);    
	}
	return undef;
}


####################################################################
#### get configuration parameters from caws.ini file            ####
####################################################################


sub load_config {
	my $inifile= shift;
	
  ### get path for ini file
  my($pack,$file,$line,$sub) = caller;
  my($dev,$dirs,$id) = File::Spec->splitpath($file);
  my $IniFile = $dev . $dirs . $inifile;

  ### check file exists
  if (!(-e $IniFile)) {
	  die "$IniFile does not exist";
  }
  
  ### get contents of ini file
  use Config::IniFiles;
  my $cfg = new Config::IniFiles( -file => $IniFile ) 
  || die "Could not read $IniFile\n";

  ### Paths
	$SITE_BASE_URL= $cfg->val('paths', 'SITE_BASE_URL');
	$SITE_BASE_DIR= $cfg->val('paths', 'SITE_BASE_DIR');
	$SITE_DATA_DIR= $cfg->val('paths', 'SITE_DATA_DIR');
	$CGI_BASE_URL= $cfg->val('paths', 'CGI_BASE_URL');
	$CGI_BASE_DIR= $cfg->val('paths', 'CGI_BASE_DIR');
	
  ### emails
	$SEND_EMAILS= $cfg->val('emails', 'SEND_EMAILS');
	$EMAIL_BASE_DIR= $cfg->val('emails', 'EMAIL_BASE_DIR');
	$MAIL_SMTP_SERVER= $cfg->val('emails', 'MAIL_SMTP_SERVER');
	$ADMIN_NAME= $cfg->val('emails', 'ADMIN_NAME');
	$ADMIN_EMAIL= $cfg->val('emails', 'ADMIN_EMAIL');
	$MAIL_SCRIPT= $cfg->val('emails', 'MAIL_SCRIPT');

	### database
	$DATABASE_NAME= $cfg->val('database', 'DATABASE_NAME');
	$DATABASE_SERVER= $cfg->val('database', 'DATABASE_SERVER');
	$DATABASE_USERNAME= $cfg->val('database', 'DATABASE_USERNAME');
	$DATABASE_PASSWORD= $cfg->val('database', 'DATABASE_PASSWORD');
	$DATABASE_TYPE= $cfg->val('database', 'DATABASE_TYPE');
	
	return;
}



1; 

